package cn.genmer.test.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    // 注入数据源
    @Autowired
    private DataSource dataSource;

//    配置对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

//    // 定义用户信息服务
//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//
//        manager.createUser(User.withUsername("genmer").password("123").authorities("p1").build());
//        manager.createUser(User.withUsername("lrh").password("123").authorities("p2").build());
//        return manager;
//    }

    // 定义密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
//
    // 定义安全拦截机制（最重要）
    protected void configure(HttpSecurity http) throws Exception{
//TODO 注释这个方法取消鉴权
//        // 配置没有权限访问跳转自定义页面
//        http.exceptionHandling().accessDeniedPage("/unauth.html");
//        // 允许表单登陆 - 自定义登录页面
//        http.formLogin()
//                .loginPage("/login.html")
//                .loginProcessingUrl("/user/login")
//                .defaultSuccessUrl("/success.html").permitAll();
//        // 自定义退出页面
//        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/index").permitAll();
//
//        http.authorizeRequests()
//                // "/", "/test/hello", "/user/login" 无需验证
//                .antMatchers("/", "/test/hello", "/user/login").permitAll()
//                // 当前登陆用户只有具有admin角色才能访问
////                .antMatchers("/user/admin").hasAuthority("admin")
////                .antMatchers("/user/role").hasAuthority("role")
//                // 当前登录用户具有多个角色中的一种就能访问 hasRole 同理
//                .antMatchers("/user/admin").hasAnyAuthority("role","common")
//                .antMatchers("/user/manager").hasAnyRole("manager")
//                // 其他请求都要验证
//                .anyRequest().authenticated()
//                // 配置自动登陆
//                .and().rememberMe().tokenRepository(persistentTokenRepository())
//                .tokenValiditySeconds(1800) // 设置有效时长,单位秒
////                .userDetailsService(userDetailsService)
//                .and()
//                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 固定用户
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("1234");
        auth.inMemoryAuthentication().withUser("root").password(password).roles("admin");
//
//        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}
